<#import "/spring.ftl" as spring />
<#import "../layout/defaultLayout.ftl" as layout>
<@layout.defaultLayout styles=["bootstrap-table/bootstrap-table.min.css",
"bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css"]
scripts=["bootstrap-table/bootstrap-table.min.js",
"bootstrap-table/locale/bootstrap-table-zh-CN.min.js",
"bootstrap-validator/validator.js",
"jquery/serializejson/jquery.serializejson.min.js",
"util/jquery-dateFormat.min.js",
"bootstrap-table/extensions/export/bootstrap-table-export.min.js",
"bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js",
"bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js",
"util/tableExport.js"]>

<div class="container-fluid">
        <div class="container">
         	 	<form class="form-inline" role="form" id="queryForm">
         	 	<input type="text" id ="reportId" name="reportId" value="${reportId}" style="display:none">
         	 	<!-- <a  data-toggle="modal" data-target="#myModal" style="cursor:pointer;">
            		Launch modal table
        		</a> -->
                    <div>
                        <div id="main-toolbar">
			        
			          <#list reportCondition as condition>
			          	<#if condition?index%4 == 0 && condition?index != 0>
			          		<div class="col-sm-3 col-md-3">
			          	</#if>
			          	<#if condition.type == '1'>

							   <div class="form-group">
							    <label for="${condition.code}">${condition.name}</label>
							    <input type="text" class="form-control" id="${condition.code}" name="${condition.code}"/>
							  </div>
				          <#elseif condition.type == '2'>
							   <div class="form-group">
							    <label for="${condition.code}">${condition.name}</label>
							    <input type="text" id="${condition.code}" value ="" name="${condition.code}" class ="form-control datetimepicker"  />
							  </div>
						  <#elseif condition.type == '3'>

				          	 <div class="form-group">
					          <label class="control-label" for="${condition.code}">${condition.name}</label>
					            <select class="form-control" id="${condition.code}" name="${condition.code}">
						  		<#if condition.comboboxType == 1>	
						  			<#if condition.code != 'DIMENSION'>
						  				<option value="">请选择</option>		
						  			</#if>				  			
						  			<#list enumList as obj>
						  				<#if obj.condition.id == condition.id>
						  					<option value="${obj.code}">${obj.name}</option>
						  				</#if>
						  			</#list>
						  		<#elseif condition.comboboxType == 2>	
						  			<option value="">请选择</option>	
						  			<#if condition.cascadeCondition??>
							  			<option class="hideOption" style="display:none;" name="${condition.cascadeCondition}" code="${condition.code}"></option>
							  		<#else>
							  			<#list conditionValList as conditionVal>
							  				<#if condition.id == conditionVal.conditionId>
							  					<option value="${conditionVal.code}">${conditionVal.name}</option>
							  				</#if>
							  			</#list>
							  		</#if>
						  		</#if>
				          		</select>		
						        </div>
				          </#if>
				          <#if condition?index%4 - 3 == 0 && condition?index != 0>
			          		</div>
			          	 </#if>
			          </#list>
			        	 <button id="queryByCondition" type="button" class="btn btn-success" >提交</button>

			      </div>
				   
				  </form>
            <div>
                <table id="table" data-classes="table table-hover table-striped" data-toolbar="#main-toolbar" data-toggle="table">

                </table>

            </div>
            <!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog" style="width:1000px;">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title" id="myModalLabel">
					
				</h4>
			</div>
			<div class="modal-body">
				<table id="modelTable" data-classes="table table-hover table-striped" data-toggle="table">

                </table>
			</div>	
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">关闭
				</button>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>
        </div>
        

</div>
<script>	
    var mTable = $('#table');
    var columns = [], datas = [];
    var flag = 0;
    var modelTable =  $('#modelTable');
    var linkItem = null;
    $('.datetimepicker').datetimepicker({
	    format: 'yyyy-mm-dd hh:ii:ss',
	    autoclose: true,
        todayBtn: true,
        todayHighlight:true,
        language:'zh-CN'
	});
	
	$("#queryByCondition").click(function(){
		datas = [];
		queryData();
	});
	
	function queryData(){
		mTable.bootstrapTable('showLoading');
		//alert("第几次查询："+flag);
		flag = flag + 1;
		//var pageNumber = JSON.stringify(mTable.bootstrapTable('getOptions').pageNumber);
		//var pageSize = JSON.stringify(mTable.bootstrapTable('getOptions').pageSize);
		var obj = $('#queryForm').serializeJSON();
		//obj.pageNumber = pageNumber;
		//obj.pageSize  = pageSize;
		var jsonString = JSON.stringify(obj);
		$.ajax({
	        url:'/report/queryColumnAndData',
	        type:'post',
	        contentType: 'application/json',
	        data:jsonString,
	        dataType:'json',
	        success:function(data){
	        	var reportColList = data.reportColList;
	        	var reportDataList =data.reportDataList;
	        	refreshTable(reportColList,reportDataList,mTable,0);
	        	$("#queryForm").setForm(obj);
	        }
		});
	}
	
	function refreshTable(reportColList,reportDataList,btTable,flag){
		if(flag == 0){
			linkItem = new Array();
		}		
		columns = [], datas = [];
		if (reportColList){
    		$.each(reportColList, function(i,item){  
    			if(flag == 0){
    				if (item.linkReport){
        				//item.name = "<a  data-toggle='modal' data-target=''#myModal'>"+item.name+"</a>";
        				linkItem[linkItem.length] = item.code;    				
        			}
    			}   			
    			//alert(item.name+":"+item.code)
        		columns.push({
                    field: item.code,                   
                    title: item.name,
                    sortable: true
                })
            });
    	}
    	if (reportDataList){
    		 var row = null;
    		 $.each(reportDataList, function(i,dataMap){  
        		 row = {};
        		 for (var key in dataMap){ 
        			 xflag = 0;
        			 for (var i in linkItem){
        			 	if (linkItem[i] == key){
        			 		row[key] = "<a class='linkClass' style＝'cursor:pointer' data-toggle='modal' data-target='#myModal' name='"+key+"'>"+dataMap[key]+"</a>";
        			 		xflag = 1;
        			 		break;
        			 	} 
        			 }
        			 if (xflag == 0){
        				 row[key] = dataMap[key];
        			 }
        		 }
        		 datas.push(row);
	            });
    	}
    	btTable.bootstrapTable('hideLoading');//hideLoading
    	btTable.bootstrapTable('refreshOptions',
                {
                    columns: columns,
                    data: datas,
                    pagination: true,
                    sidePagination: 'client',
                    pageList: [5, 10, 20]
                }
        )
        
	}
	
    $(function () {
    	if (flag == 0){
    		queryData();
    	}
    	   	
    	$('#myModal').on('show.bs.modal', function () {    		
    		
        });

    	mTable.on('click-cell.bs.table', function (e,field, value, row, $element) {  
    		modelTable.bootstrapTable('showLoading');//hideLoading
    		//alert(linkItem)
    		cellFlag = 0;
    		for (var i in linkItem){
			 	if (linkItem[i] == field){
			 		cellFlag = 1;
			 	} 
			 }
    		if (cellFlag == 0){
    			return ;
    		}
    		
    		//row. = value.substring(value.indexOf(">")+1,value.lastIndexOf("<"));
    		var paramObj = row;
    		paramObj.reportId = $("#reportId").val();
    		paramObj.colunmName = field;
    		var objForm = $('#queryForm').serializeJSON();
    		//alert(JSON.stringify(objForm))
    		for (var code in objForm){
    			if (typeof(paramObj[code]) == 'undefined'){
    				paramObj[code] = objForm[code];
    			}
    		}
    		//alert(JSON.stringify(paramObj))
    		$.ajax({
    	        url:'/report/queryDrillReport',
    	        type:'post',
    	        contentType: 'application/json',
    	        data:JSON.stringify(paramObj),
    	        dataType:'json',
    	        success:function(data){
    	        	var reportColList = data.reportColList;
    	        	var reportDataList =data.reportDataList;
    	        	var drillReportTitle = data.drillReportTitle;
    	        	$("#myModalLabel").html(drillReportTitle);
    	        	refreshTable(reportColList,reportDataList,modelTable,1);  
    	        	
    	        }
    		});
    	});
    	$("select").change(function(){
    		selectId = $(this).attr('id');
    		options = $("option.hideOption").attr('name');
    		linkCode = $("option.hideOption").attr('code');
    		//reportId = $("#reportId").val();
    		//for (var i in options){
    			if (selectId == options){
    				$("select#"+linkCode).empty();
    				$("select#"+linkCode).append("<option value=''>请选择</option>");
    				$("select#"+linkCode).append("<option class='hideOption' style='display:none;' name='"+options+"' code='"+linkCode+"'></option>");
    				if ($(this).val() ==''){
    					return;
    				}
    				$.ajax({
    	    	        url:'/report/queryConditionVal',
    	    	        type:'post',
    	    	        contentType: 'application/json',
    	    	        data:JSON.stringify({"reportId":$("#reportId").val(),"paramName":selectId,"paramValue":$(this).val(),"linkCode":linkCode}),
    	    	        dataType:'json',
    	    	        success:function(data){
    	    	        	 $.each(data, function(i,dataMap){
    	    	        		$("select#"+linkCode).append("<option value='"+dataMap['CODE']+"'>"+dataMap['NAME']+"</option>");
    	    	        		
    	    		        }); 
    	    	        }
    	    		});
    			}
    		//}
    	});

        /**for (var i = 0; i < 10; i++) {
            columns.push({
                field: 'field' + i,
                title: 'Cell' + i,
                sortable: true
            })
        }

        var row = null
        for (i = 0; i < 3; i++) {
            row = {};
            for (var j = 0; j < 10; j++) {
                row['field' + j] = i*j;
            }
            data.push(row)
        }*/
    })
    
    /**
 * 将josn对象赋值给form
 * @param {dom} 指定的选择器
 * @param {obj} 需要给form赋值的json对象
 * @method serializeJson
 * */
$.fn.setForm = function(jsonValue){
  var obj = this;
  $.each(jsonValue,function(name,ival){
    var $oinput = obj.find("input[name="+name+"]");
    if($oinput.attr("type")=="checkbox"){
      if(ival !== null){
        var checkboxObj = $("[name="+name+"]");
        var checkArray = ival.split(";");
        for(var i=0;i<checkboxObj.length;i++){
          for(var j=0;j<checkArray.length;j++){
            if(checkboxObj[i].value == checkArray[j]){
              checkboxObj[i].click();
            }
          }
        }
      }
    }
    else if($oinput.attr("type")=="radio"){
      $oinput.each(function(){
        var radioObj = $("[name="+name+"]");
        for(var i=0;i<radioObj.length;i++){
          if(radioObj[i].value == ival){
            radioObj[i].click();
          }
        }
      });
    }
    else if($oinput.attr("type")=="textarea"){
      obj.find("[name="+name+"]").html(ival);
    }
    else{
      obj.find("[name="+name+"]").val(ival);
    }
  })
}

</script>
</@layout.defaultLayout>